import React, { useEffect, useState } from 'react'
import { usePieceStore } from '@/store/piece'
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area'
import ResultTable from './ResultTable'
import {
  calculateTotalScore,
  calResultEffect,
  DEFAULT_SCORE_COUNT,
  JEWEL_SCORE_COUNT
} from '@/utils/pieceAnalysis'
import { Button } from '@/components/ui/button'

import type { Piece } from '@/types/piece'
import type { pieceState } from '@/store/piece'
export interface ResultProps {
  pieces: (Piece | undefined)[]
  hasJewel?: boolean // 是否有首饰
  handle_result: (text: string) => void
  equipColumnNames: string[]
  jewelryColumnNames: string[]
}
const Result: React.FC<ResultProps> = ({
  pieces,
  hasJewel,
  handle_result,
  equipColumnNames,
  jewelryColumnNames
}) => {
  const [showDetailCols, setShowDetailCols] = useState(false)
  const storePieceProps = usePieceStore(
    (state: pieceState) => state.storePieceProps
  )
  const loadPiecePropsFromStore = usePieceStore(
    (state: pieceState) => state.loadPieceProps
  )

  useEffect(() => {
    loadPiecePropsFromStore()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  const scoreCount = hasJewel ? JEWEL_SCORE_COUNT : DEFAULT_SCORE_COUNT
  const totalScore = calculateTotalScore(pieces, storePieceProps, scoreCount)

  useEffect(() => {
    if (totalScore.length > 0) {
      const header = ['属性', '合计', '效果'].join('\t')
      const resultText = totalScore
        .map(
          (item) =>
            `${item.title}\t${item.result}\t${calResultEffect(
              item.result,
              item.effect
            )}`
        )
        .join('\n')
      handle_result(`${header}\n${resultText}`)
    } else {
      handle_result('')
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pieces, totalScore])

  return (
    <div className="py-6">
      <h2 className="mb-6 text-2xl font-bold">碎片效果</h2>
      <div className="mb-4 flex items-center gap-4">
        <Button variant={'ghost'} onClick={() => setShowDetailCols((v) => !v)}>
          {showDetailCols ? '隐藏明细列' : '显示明细列'}
        </Button>
      </div>
      <ScrollArea
        className={`w-full overflow-auto py-4${
          showDetailCols ? '' : ' min-w-0'
        }`}
      >
        <ResultTable
          totalScore={totalScore}
          showDetailCols={showDetailCols}
          hasJewel={!!hasJewel}
          scoreCount={scoreCount}
          equipColumnNames={equipColumnNames}
          jewelryColumnNames={jewelryColumnNames}
        />
        {!showDetailCols ? null : <ScrollBar orientation="horizontal" />}
      </ScrollArea>
    </div>
  )
}

export default Result
